//
//  AppDelegate.m
//  InviteJob
//
//  Created by chirui on 2017/10/13.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarVc.h"
#import "LoginViewController.h"
#import "LeadVC.h"
// 引入JPush功能所需头文件
#import <JPUSHService.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#import <WXApi.h>

@interface AppDelegate ()<JPUSHRegisterDelegate,WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window =[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor =[UIColor whiteColor];
    
    if ([USER_DEFAULTGet(@"version") isEqualToString:@"V1.0.0"]) {
         self.window.rootViewController = [[TabBarVc alloc]init];
    }else{
        self.window.rootViewController = [[LeadVC alloc]init];
    }
  
    [self.window makeKeyWindow];
    
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    // 微信注册
    [WXApi registerApp:@"wx5bf54ed6460a98b8"];
    
    // jPush
    [self jPush:launchOptions];
    
    return YES;
}

#pragma mark - 极光推送
-(void)jPush:(NSDictionary *)launchOptions{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber -= 1;
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //         可以添加自定义categories
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:@"c92e7446b548558ee0014dbe"
                          channel:@"ios"
                 apsForProduction:TRUE
            advertisingIdentifier:nil];
//    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    // 注册绑定别名通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindAlia:) name:@"bindAlia" object:nil];
    
  
    UIUserNotificationSettings *settings=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
// 绑定别名
- (void)bindAlia:(NSNotification *)notification{
    
    isUser
    NSString *alias;
    if ([notification.object isEqualToString:@"YES"]) {//绑定
        alias = user.user_id;
    }else{//解绑
        alias = @"";
    }
    
    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        
        if (iResCode == 0) {//对应的状态码返回为0，代表成功
            
            [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
        }
    }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        NSString *apnCount = userInfo[@"aps"][@"alert"];
        NSLog(@"消息 = %@",apnCount);
        
        UILocalNotification *localNotification = [[UILocalNotification alloc]init];
        //触发通知时间
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.1];
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        //重复间隔
        //    localNotification.repeatInterval = kCFCalendarUnitMinute;
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        
        //通知内容
        localNotification.alertBody =apnCount;
        localNotification.applicationIconBadgeNumber =1;
        
        
        //通知参数
        localNotification.userInfo =@{@"kLocalNotificationKey":apnCount};
        
        localNotification.category =@"kNotificationCategoryIdentifile";
        
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
        
    }else{
       
    }
    
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [WXApi handleOpenURL:url delegate:self];
}


- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    
    if ([url.host isEqualToString:@"pay"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}

#pragma mark 微信回调方法

- (void)onResp:(BaseResp *)resp
{
    NSString * strTitle;
    //判断是微信消息的回调 --> 是支付回调回来的还是消息回调回来的.
    if ([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息的结果"];
    }
    
    NSString * wxPayResult;
    //判断是否是微信支付回调 (注意是PayResp 而不是PayReq)
    
    if ([resp isKindOfClass:[PayResp class]])
    {
        //支付返回的结果, 实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode)
        {
            case WXSuccess:
            {
                wxPayResult = @"1";
                break;
            }
            case WXErrCodeUserCancel:
            {
                wxPayResult = @"2";
                break;
            }
            default:
            {
               wxPayResult = @"3";
                break;
            }
        }
        //发出通知 从微信回调回来之后,发一个通知,让请求支付的页面接收消息,并且展示出来,或者进行一些自定义的展示或者跳转
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"WXPayNotification" object:nil userInfo:@{@"WXPayNotification":wxPayResult}];
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
